-- metscrape - bulk-download weather forecasts.
-- Copyright (C) 2013  Jack Kelly <jack@jackkelly.name>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

module Menu (Menu, run) where

import Control.Arrow
import Data.Char
import qualified Data.Map as Map
import Scraper
import System.IO
import Text.Printf

type Menu = [(String, Scraper)]

printItems :: Menu -> IO ()
printItems items =
    let labels = zipWith (printf "%c) %s") ['A'..'Z'] (map fst items) in
    mapM_ putStrLn labels

-- Return the menu entries that are actually selected.
menu :: Menu -> IO Menu
menu items = do
  printItems items
  putStr "\nEnter the options to grab, or * for all: "
  hFlush stdout
  line <- fmap (\str -> [ toUpper c | c <- str, c == '*' || isAlpha c ]) getLine
  if '*' `elem` line
  then return items
  else do
    let table = Map.fromList $ zip ['A' .. 'Z'] items
        selected = filter (/= '*') line
    return $ map (table Map.!) selected

fetch :: (String, Scraper) -> IO ()
fetch (label, scraper) = do
  let line = replicate (length label) '='
  putStrLn $ line
  putStrLn $ label
  putStrLn $ line
  scrape scraper

copyright :: IO ()
copyright =
    putStrLn "metscrape  Copyright (C) 2013  Jack Kelly <jack@jackkelly.name>\n\
             \This program comes with ABSOLUTELY NO WARRANTY.\n\
             \This is free software, and you are welcome to redistribute it\n\
             \under certain conditions; see the GNU GPL version 3 (or later)\n\
             \for details.\n"

run :: Menu -> IO ()
run choices = do
  copyright
  menu choices >>= mapM_ fetch
